using System;
using System.Data;
using System.IO;
using System.Text;

namespace FreeFlow.Administration
{
	/// <summary>
	/// An attachment in the database.
	/// </summary>
	public class Attachment : DatabaseAware, IDeletable
	{
		internal Attachment(Server server, IDataReader reader) : base(server)
		{
      if (reader["eSize"] != System.DBNull.Value)
        size = Convert.ToInt32(reader["eSize"]);
      ParseKey(reader["eKey"].ToString(), out type, out owner, out fileName);
		}

    internal static void ParseKey(string key, out AttachmentType type, out string owner, out string fileName)
    {
      string[] keyParts = key.Split('\t');
      int attType = int.Parse(keyParts[0]);
      type = (AttachmentType)attType;
      owner = keyParts[1];
      fileName = keyParts[2];
    }

    internal static string ByteArrayToString(byte[] data)
    {
      if (data == null)
        return "";

      using (MemoryStream stream = new MemoryStream(data))
      {
        StreamReader reader = new StreamReader(stream, Encoding.UTF8);
        return reader.ReadToEnd();
      }
    }

    private int size;
    /// <summary>
    /// Gets the size of the attachment.
    /// </summary>
    public int Size
    {
      get
      {
        return size;
      }
    }

    private string fileName;
    /// <summary>
    /// Gets the file name of the attachment.
    /// </summary>
    public string FileName
    {
      get
      {
        return fileName;
      }
    }

    private AttachmentType type;
    /// <summary>
    /// Gets the type of attachment.
    /// </summary>
    public AttachmentType Type
    {
      get
      {
        return type;
      }
    }

    private string owner;
    /// <summary>
    /// Gets the owner of the attachment (folder ID for folder attachments, map name for map attachments, procedure name for procedure attachments).
    /// </summary>
    public string Owner
    {
      get
      {
        return owner;
      }
    }

    /// <summary>
    /// Gets the attachment data as a byte array.
    /// </summary>
    public byte[] GetData()
    {
      return Server.GetAttachment(type, fileName, owner);
    }

    /// <summary>
    /// Saves the attachment to a file.
    /// </summary>
    /// <param name="fileName">Name of the file to save to.</param>
    public void SaveToFile(string fileName)
    {
      Server.SaveAttachmentToFile(type, this.fileName, owner, fileName);
    }

    #region IDeletable Members

    /// <summary>
    /// Deletes this attachment from the database.
    /// </summary>
    public void Delete()
    {
      Server.DeleteAttachment(type, this.fileName, owner); 
    }

    #endregion
  }
}
